/*AyflEomXWyqCHfdTxzWda+bKRNxqoRhrf02Huevr4hQ=*/
//主子表列表

import { base, createPage, high, print, ajax, toast, cardCache, cacheTools, getMultiLang} from 'nc-lightapp-front';
import React, { Component } from 'react';
import CombinedExaminationModel from '../../../public/components/combinedExaminationModel'; //联查处理情况
import LinkTerm from '../../../public/components/linkTerm'; //联查收付款协议
import { getButtonsKey, onListButtonControl } from '../../../public/components/pubUtils/buttonvisible';
import { searchId, tableId, nodekey, billType, pkname, dataSource, searchKey, tradeType } from './constants';
import { buttonClick, initTemplate, pageInfoClick, searchBtnClick, tableModelConfirm, doubleClick } from './events';
import linkSourceList from '../../../public/components/linkSourceList.js';
import cmpLinkArapList from '../../../public/components/cmpLinkArapList.js';
import { getContext, loginContextKeys } from '../../../public/components/arapInitInfo/loginContext';
import TradeTypeButton from '../../../public/components/tradetype'; //交易类型按钮
import afterEvent from '../../../public/components/searchAreaAfterEvent'; //查询区编辑后事件
import '../../../public/less/tradetype.less';
import InvoiceLink from 'sscivm/ivmpub/components/invoice-link';
import Inspection from 'epmp/exports/components/Inspection';
import {listSocketConnect} from '../../../public/components/pubUtils/MicroServiceSocket.js';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import ExcelOutput from 'uap/common/components/ExcelOutput';
import NCUploader from 'uap/common/components/NCUploader';
import ApprovalTrans from 'uap/common/components/approvalTrans';
const { NCDiv } = base;
let { BillTrack, PrintOutput} = high;
let { setDefData, getDefData, getCacheById, getCurrentLastId } = cardCache;

class List extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isCombinedExaminationModelShow: false, //联查处理情况模态框
			isLinkTermModelShow: false, //联查收付款协议模态框
			isTbbLinkshow: false, //控制联查执行预算的模态框
			showBillTrack: false,
			showApproveDetail: false, //是否显示审批详情模态框
			showUploader: false, //附件管理
			target: null, //附件管理
			compositedisplay: false,
			json: {},
			forceRender: true,//导出模板懒加载，true为不加载，false为加载
			sscivmInvoiceData: {} //联查发票
		};
		this.printData = {
			billtype: billType, //单据类型
			appcode: props.getSearchParam('c') ? props.getSearchParam('c') : props.getUrlParam('c'), //功能节点编码，即模板编码
			nodekey: nodekey, //模板节点标识
			oids: null, // 功能节点的数据主键
			userjson: billType //单据类型,billtype不是必需字段，后台没有设置接收字段，以userjson代替
		};
		this.outputData = {
			billtype: billType, //单据类型
			appcode: props.getSearchParam('c') ? props.getSearchParam('c') : props.getUrlParam('c'), //功能节点编码，即模板编码
			funcode: props.getSearchParam('c') ? props.getSearchParam('c') : props.getUrlParam('c'),
			nodekey: nodekey, //模板节点标识
			oids: null, // 功能节点的数据主键
			userjson: billType, //单据类型,billtype不是必需字段，后台没有设置接收字段，以userjson代
			outputType: 'output'
		};
		this.searchId = searchId;
		this.tableId = tableId;
		this.billType = billType;
		this.pkname = pkname;
		this.pageId = props.getSearchParam('p');
		let { search } = this.props;
		let { setSearchValByField, getAllSearchData } = search;
		this.setSearchValByField = setSearchValByField; //设置查询区某个字段值
		this.getAllSearchData = getAllSearchData; //获取查询区所有字段数据
		this.Info = {
			//全局变量,不需要涉及重绘页面的数据存贮
			allButtonsKey: [], //保存所有的头部按钮
			pullBillInfoVOAry: [], //拉单使用
			tipContent: '', //提示框Content
			tipUrl: null, //提示框二次交互的url
			exType: null, //异常类型，现为三种（1,2,3）
			record: null, //点提交时当前行数据
			flag: false, //提交收回异常交互参数值，默认为false
			billCode: '', // 发票号
			linkTermData: [], //联查收付款协议模态框表格数据
			tbbLinkSourceData: null, //联查执行预算的数据
			combinedExaminationData: [], //联查处理情况模态框表格数据
			selectedPKS: [], //导出数据的主键pk
			pk_bill: null, //当前选中第一行的主键pk
			ts: null,
			approvestatus: null, //当前选中第一行的审批状态
			index: null, //保存当前选中第一行的行号index
			pk_tradetypeid: null, //当前选中第一行行的交易类型
			pk_tradetype: null, //当前选中第一行行的交易类型
			billno: null, //当前选中第一行的单据号
			compositedata: null //指派信息处理
		};
		this.dataInSaga = {    //用于saga里面的busiinfo
			appcode: props.getSearchParam('c') ? props.getSearchParam('c') : null,
			pagecode: props.getSearchParam('p') ? props.getSearchParam('p') : null,
			butncode: null
		}
		props.use.search(searchId);
		props.use.table(tableId);
	}

	componentWillReceiveProps(nextProps) {}

	componentWillMount() {
		if (getDefData('scene', dataSource) == 'bz') {
			this.dealBzScence();
		} else {
			let callback = (json) => {
				this.setState({ json: json }, () => {
					initTemplate.call(this, this.props, this.initShow);
				});
			};
			getMultiLang({ moduleId: [ 'payablebill','public' ], domainName: 'arap', currentLocale: 'simpchn', callback });
		}
	}

	getPagecode = () => {
		let pagecode = null;
		if (this.props.getUrlParam('scene') || this.props.getSearchParam('p') == '20080PBM_LIST_LINK') {
			if (!this.props.getUrlParam('scene')) {
				////浏览器的刷新可能导致场景丢失，这里自己塞一次
				this.props.ViewModel.setData('nccloud-router-params', { scene: 'linksce' });
			}
			pagecode = '20080PBM_LIST_LINK';
		} else {
			pagecode = '20080PBM_LIST';
		}

		return pagecode;
	};

	//在第一次渲染后调用
	componentDidMount() {}

	initShow = () => {
		this.onSelected(); //缓存不存在，就控制按钮
		if (!this.props.table.hasCacheData(dataSource)) {			
			if (this.props.getUrlParam('src') == 'widget') {
				let RecToDoSearchVO = cacheTools.get('F1widget');
				let pageInfo = this.props.table.getTablePageInfo(this.tableId);
				let queryInfo = {
					pageInfo: pageInfo,
					queryAreaCode: this.searchId, //查询区编码
					oid: '1001Z310000000010C6L',
					querytype: 'tree'
				};
				let data = {
					pageId: this.props.getSearchParam('p'),
					queryInfo: queryInfo,
					toDoSearchVO: RecToDoSearchVO
				};
				ajax({
					url: '/nccloud/arap/payablebill/querywidget.do',
					data: data,
					success: (res) => {
						let { data } = res;
						if (data) {
							this.props.table.setAllTableData(this.tableId, data[this.tableId]);
						} else {
							toast({
								color: 'success',
								content: this.state.json['payablebill-000017']
							}); /* 国际化处理： 未查询到数据*/
							this.props.table.setAllTableData(this.tableId, { rows: [] });
						}
						setDefData(this.tableId, dataSource, data); //放入缓存
					}
				});
			} else if ('browse' == this.props.getUrlParam('status')) {
				//联查
				if ('fip' == this.props.getUrlParam('scene')) {
					linkSourceList(this.props, this.tableId);
				} else if (
					this.props.getUrlParam('scene') == 'linksce' &&
					this.props.getUrlParam('flag') == 'ftsLinkArap'
				) {
					cmpLinkArapList(this.props, this.tableId, this.billType);
				}
			} else if (cacheTools.get('36D1linkF1')) {
				let pageInfo = this.props.table.getTablePageInfo(this.tableId);
				let queryInfo = {
					pageInfo: pageInfo,
					queryAreaCode: this.searchId,
					oid: '1001Z310000000010C6L',
					querytype: 'tree'
				};
				let data = {
					pageId: this.props.getSearchParam('p'),
					queryInfo: queryInfo,
					pk_bills: cacheTools.get('36D1linkF1')
				};
				ajax({
					url: '/nccloud/arap/payablebill/querywithpks.do',
					data: data,
					success: (res) => {
						let { data } = res;
						if (data) {
							this.props.table.setAllTableData(this.tableId, data[this.tableId]);
						} else {
							toast({
								color: 'success',
								content: this.state.json['payablebill-000017']
							}); /* 国际化处理： 未查询到数据*/
							this.props.table.setAllTableData(this.tableId, { rows: [] });
						}
						setDefData(this.tableId, dataSource, data); //放入缓存
					}
				});
			}
		}
		let isSwitchTradeType = getDefData('isSwitchTradeType', dataSource);
		if (isSwitchTradeType) {
			//如果卡片切换过交易类型的话，列表返回卡片需要重新刷新列表按钮
			this.switchTemplate.call(this);
		}
	};

	//处理报账平台返回到列表界面的场景
	dealBzScence = () => {
		let id = getCurrentLastId(dataSource);
		if (id) {
			let cardData = getCacheById(id, dataSource);
			let pagecode = cardData.head.head.rows[0].values.pk_tradetype.value;
			let pk_payablebill = cardData.head.head.rows[0].values.pk_payablebill.value;
			this.props.pushTo('/card', {
				status: 'browse',
				id: pk_payablebill,
				pagecode: pagecode,
				scene: 'bz'
			});
		} else {
			this.props.pushTo('/card', {
				status: 'browse',
				pagecode: getDefData('pagecode', dataSource),
				scene: 'bz'
			});
		}
	};

	// 附件的关闭点击
	onHideUploader = () => {
		this.setState({
			showUploader: false
		});
	};

	//列表控制按钮
	onSelected = () => {
		onListButtonControl(this);
	};

	//联查处理情况按钮
	handleCombined = () => {
		this.setState({
			isCombinedExaminationModelShow: true
		}, () => {
			if (this.state.isCombinedExaminationModelShow) {
				this.child.modalOpen();
			} else {
				this.child.modalClose();
			}
		});
	};
	onRender = (ref) => {
		this.child = ref;
	};
	//联查收付款协议
	handleLinkTerm = () => {
		this.setState({
			isLinkTermModelShow: true
		},() => {
			if (this.state.isLinkTermModelShow) {
				this.child2.modalOpen();
			} else {
				this.child2.modalClose();
			}
		});
	};
	onRenderTerm =(ref)=>{
		this.child2 = ref;
	}	

	//设置当前选中行数据的ts的值
	setFormTsVal = (ts) => {
		if (this.Info.index) {
			let tsCell = { value: ts, display: '', scale: -1 };
			this.props.table.setValByKeyAndIndex(this.tableId, this.Info.index, 'ts', tsCell);
		}
	};

	//关闭联查执行预算的模态框
	tbbLinkcancel() {
		this.setState({
			isTbbLinkshow: false
		});
	}

	//打印
	onPrint = () => {
		print(
			'pdf', //支持两类: 'html'为模板打印, 'pdf'为pdf打印
			'/nccloud/arap/arappub/print.do', //后台服务url
			this.printData,
			false
		);
	};

	//正式打印
	officalPrintOutput = () => {
		ajax({
			url: '/nccloud/arap/arappub/officialPrint.do',
			data: this.printData,
			async: false,
			success: (res) => {
				if (res.success) {
					print(
						'pdf', //支持两类: 'html'为模板打印, 'pdf'为pdf打印
						'/nccloud/arap/arappub/print.do', //后台服务url
						this.printData
					);
				}
			}
		});
	};
	//取消正式打印
	cancelPrintOutput = () => {
		ajax({
			url: '/nccloud/arap/arappub/cancelPrint.do',
			data: this.printData,
			async: false,
			success: (res) => {
				if (res.success) {
					//取消正式打印提示框
					toast({ color: 'success', content: res.data });
				}
			}
		});
	};

	//审批详情模态框控制
	closeApprove = () => {
		this.setState({
			showApproveDetail: false
		});
	};

	//输出
	printOutput = () => {
		this.refs.printOutput.open();
	};
	//输出成功回调函数
	onSubmit() {}

	//提交和收回弹框点击取消
	clearExType = () => {
		this.Info.exType = null;
		this.Info.flag = true;
		this.Info.compositedata = null;
		this.Info.tipUrl = null;
		if (this.state.compositedisplay) {
			this.setState({ compositedisplay: false });
		}
	};

	//提交and收回公共调用函数
	commitAndUncommit = () => {
		let tipUrl = this.Info.tipUrl;
		let extype = this.Info.exType;
		let flag = this.Info.flag;
		let record = this.Info.record;
		ajax({
			url: tipUrl,
			data:Object.assign({
				pk_bill: record.pk_payablebill.value,
				ts: record.ts.value,
				pageId: this.props.getSearchParam('p'),
				billType: this.billType,
				type: 1,
				extype: extype,
				flag: flag,
				assignObj: this.Info.compositedata
			},this.dataInSaga) ,
			success: (res) => {
				if (res.data.exType == '1') {
					let content = res.data.message;

					this.Info.tipContent = content;
					this.Info.exType = '1';
					this.Info.flag = true;

					this.props.modal.show('commitAndUncommit');
					return;
				} else if (
					res.data.workflow &&
					(res.data.workflow == 'approveflow' || res.data.workflow == 'workflow')
				) {
					this.Info.compositedata = res.data;
					this.Info.tipUrl = tipUrl;
					this.setState({ compositedisplay: true });
					return;
				}
				if (res.success) {
					this.clearExType();
					toast({ color: 'success', content: this.state.json['payablebill-000031'] }); /* 国际化处理： 操作成功*/
					//更新当前行数据
					this.props.table.updateDataByIndexs(this.tableId, [
						{ index: record.numberindex.value - 1, data: { values: res.data[this.tableId].rows[0].values } }
					]);
					this.onSelected();
				}
			}
		});
	};

	delConfirm = (extype, flag) => {
		ajax({
			url: '/nccloud/arap/arappub/delete.do',
			data: [
				Object.assign({
					pk_bill: this.Info.pk_bill,
					ts: this.Info.ts,
					billType: this.billType,
					extype: extype,
					index: this.Info.index,
					flag: flag
				},this.dataInSaga)
			],
			success: (res) => {
				let { success, data } = res;
				if (success) {
					if (data) {
						if (res.data.exType == '1') {
							this.Info.tipContent = res.data.message;
							this.Info.exType = '1';
							this.Info.flag = true;
							this.props.modal.show('deleteCheck');
							return;
						} else {
							toast({
								color: data.PopupWindowStyle,
								content: data.errMsg
							});
							//删除当前行数据
							this.props.table.deleteTableRowsByIndex(this.tableId, data.successIndexs);
							//删除缓存数据
							this.props.table.deleteCacheId(this.tableId, data.successPKs);
							//删行之后控制肩部按钮
							this.onSelected();
							this.clearExType();
						}
					}
				}
			}
		});
	};

	//单据删除模态框确定按钮点击事件
	deleteBillSureBtnClick = () => {
		let exType = this.Info.exType;
		let flag = this.Info.flag;
		this.delConfirm(exType, flag);
	};

	switchTemplate = () => {
		//initTemplate.call(this, this.props);
		//列表切换交易类型的时候只切换按钮
		let pagecode = this.getPagecode();
		let appcode = this.props.getSearchParam('c') ? this.props.getSearchParam('c') : this.props.getUrlParam('c');
		let tradetype = getDefData('sessionTradeType', dataSource);
		if (!tradetype) {
			tradetype = tradeType;
		}
		ajax({
			url: '/nccloud/arap/arappub/queryallbtns.do',
			data: {
				appcode: appcode,
				pagecode: pagecode,
				tradetype: tradetype,
				billtype: billType
			},
			success: (res) => {
				let data = res.data;
				if (data.button) {
					let button = data.button;
					this.Info.pullBillInfoVOAry = data.pullbillinfo;
					getButtonsKey(button, this.Info.allButtonsKey);
					this.props.button.setButtons(button);
				}
			}
		});
	};

	// 查询区渲染完成回调函数
	renderCompleteEvent = () => {
		let cachesearch = getDefData(searchKey, dataSource);
		if (cachesearch && cachesearch.conditions) {
			// this.props.search.setSearchValue(this.searchId, cachesearch);
			for (let item of cachesearch.conditions) {
				if (item.field == 'billdate') {
					// 时间类型特殊处理
					let time = [];
					time.push(item.value.firstvalue);
					time.push(item.value.secondvalue);
					this.props.search.setSearchValByField(this.searchId, item.field, {
						display: item.display,
						value: time
					});
				} else {
					this.props.search.setSearchValByField(this.searchId, item.field, {
						display: item.display,
						value: item.value.firstvalue
					});
				}
			}
		}
	};
	render() {
		let { table, search, modal } = this.props;
		const { createBillHeadInfo } = this.props.BillHeadInfo;
		let { createSimpleTable } = table;
		let { NCCreateSearch } = search;
		let { createModal } = modal;
		let { showUploader, target } = this.state;
		return (
			<div className="nc-bill-list">
				{listSocketConnect.call(this)}
				<NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
						<div className="header-title-search-area">
							{createBillHeadInfo({
								title:this.props.getSearchParam('n')?this.props.getSearchParam('n'):this.state.json['payablebill-000058'],//国际化处理： 应付单
								initShowBackBtn: false,
							})}
						</div>
						<div className="header-button-area">
							{/* {交易类型按钮，默认场景} */}
							{!this.props.getUrlParam('scene') && !getContext(loginContextKeys.transtype) ? (
								<div className="trade-type">
									{TradeTypeButton({
										ref: 'tradetypeBtn',
										billtype: 'F1',
										dataSource: dataSource,
										switchTemplate: this.switchTemplate.bind(this)
									})}
								</div>
							) : null}
							{this.props.button.createButtonApp({
								area: 'list_head',
								buttonLimit: 3,
								onButtonClick: buttonClick.bind(this),
								popContainer: document.querySelector('.header-button-area')
							})}
						</div>
				</NCDiv>   
				<div className="nc-bill-search-area">
					{NCCreateSearch(
						this.searchId, //模块id
						{
							clickSearchBtn: searchBtnClick.bind(this), //   点击按钮事件
							showAdvBtn: true, //  显示高级按钮
							onAfterEvent: afterEvent.bind(this),
							renderCompleteEvent: this.renderCompleteEvent // 查询区渲染完成回调函数
						}
					)}
				</div>
				<div className="nc-bill-table-area">
					{createSimpleTable(this.tableId, {
						fieldid: "payablebill",
						dataSource: dataSource,
						pkname: pkname,
						handlePageInfoChange: pageInfoClick.bind(this),
						tableModelConfirm: tableModelConfirm,
						showCheck: true,
						showIndex: true,
						onRowDoubleClick: doubleClick.bind(this),
						onSelected: this.onSelected.bind(this),
						onSelectedAll: this.onSelected.bind(this),
						selectedChange:(...params)=>{
							this.onSelected.call(this)
						   },
						high_selectable: {
							enable: true  //默认为true
						},
						// 框选
						onBatchSelected: (...params) => {
							this.onSelected.call(this)
						},
						componentInitFinished: () => {
							this.onSelected();
						}
					})}
				</div>
				{/* 单据追溯组件 */}
				<BillTrack
					show={this.state.showBillTrack}
					close={() => {
						this.setState({ showBillTrack: false });
					}}
					pk={this.Info.pk_bill} //单据id
					type={this.Info.pk_tradetype} //单据类型
				/>

				{/* {联查处理情况} */}
				<CombinedExaminationModel
					show={this.state.isCombinedExaminationModelShow}
					combinedExaminationData={this.Info.combinedExaminationData}
					pk_tradetypeid={this.Info.pk_tradetypeid}
					billno={this.Info.billno}
					handleModel={this.handleCombined.bind(this)}
					onRef={this.onRender}
				/>
				{/* {联查发票} */}
				<InvoiceLink {...this.state.sscivmInvoiceData} table={this.props.table} />
				{/* {联查收付款协议} */}
				<LinkTerm
					show={this.state.isLinkTermModelShow}
					linkTermData={this.Info.linkTermData}
					handleModel={this.handleLinkTerm.bind(this)}
					moduleId={'2008'}
					billType={this.billType}
					pk_bill={this.Info.pk_bill}
					setFormTsVal={this.setFormTsVal.bind(this)}
					onRef={this.onRenderTerm}
				/>

				{/* {打印输出} */}
				<PrintOutput
					ref="printOutput"
					url="/nccloud/arap/arappub/outPut.do"
					data={this.outputData}
					callback={this.onSubmit}
				/>
				{/* {导入} */}
				{createModal('importModal', {
					noFooter: true,
					className: 'import-modal',
					hasBackDrop: false
				})}
				<ExcelOutput
					{...Object.assign(this.props)}
					moduleName="arap" //模块名
					billType={billType} //单据类型
					pagecode="20080PBM_CARD"
					appcode={
						this.props.getSearchParam('c') ? this.props.getSearchParam('c') : this.props.getUrlParam('c')
					}
					selectedPKS={this.Info.selectedPKS}
					exportTreeUrl={"/nccloud/arap/payablebill/payablebillexport.do"}
					forceRender = {this.state.forceRender}
				/>

				{/* {审批详情} */}
				<ApproveDetail
					show={this.state.showApproveDetail}
					close={this.closeApprove}
					billtype={this.Info.pk_tradetype}
					billid={this.Info.pk_bill}
				/>
				{showUploader && (
					<NCUploader
						billId={this.Info.pk_bill}
						billNo={this.Info.billno}
						target={target}
						placement={'bottom'}
						onHide={this.onHideUploader}
					/>
				)}
				{/* 联查计划预算 */}
				<Inspection
					show={this.state.isTbbLinkshow}
					sourceData={this.Info.tbbLinkSourceData}
					cancel={this.tbbLinkcancel.bind(this)}
				/>
				{/* 异常模态框 */}
				<div>
					{createModal('commitAndUncommit', {
						title: this.state.json['payablebill-000054'], //'预算异常提示信息',//'预算异常提示信息',//this.state.json['10170406-000017'],// 异常提示/* 国际化处理： 提示信息*/
						content: this.Info.tipContent, // '预算不通过!',//this.modalContent.call(this), //弹框内容，可以是字符串或dom
						closeModalEve:()=>{
							this.Info.flag = true
							this.Info.exType=null
						},
						beSureBtnClick: this.commitAndUncommit.bind(this), //点击确定按钮事件
						cancelBtnClick: this.clearExType.bind(this) //提交和收回取消事件
					})}
					{createModal('deleteCheck', {
						title: this.state.json['payablebill-000054'], //'预算异常提示信息',//'预算异常提示信息',//this.state.json['10170406-000017'],// 异常提示/* 国际化处理： 提示信息*/
						content: this.Info.tipContent, // '预算不通过!',//this.modalContent.call(this), //弹框内容，可以是字符串或dom
						closeModalEve:()=>{
							this.Info.flag = true
							this.Info.exType=null
						},
						beSureBtnClick: this.deleteBillSureBtnClick.bind(this) //点击确定按钮事件
					})}
					{/* 指派信息弹框 */}
					{this.state.compositedisplay ? (
						<ApprovalTrans
							title={this.state.json['payablebill-000055']} /* 国际化处理： 指派*/
							data={this.Info.compositedata}
							display={this.state.compositedisplay}
							getResult={this.commitAndUncommit.bind(this)}
							cancel={this.clearExType.bind(this)}
						/>
					) : null}
				</div>
			</div>
		);
	}
}

List = createPage({})(List);

export default List;

/*AyflEomXWyqCHfdTxzWda+bKRNxqoRhrf02Huevr4hQ=*/